package com.uniflow.service;

import com.alibaba.fastjson2.JSON;

import com.uniflow.entity.DataSync;
import com.uniflow.entity.DataSyncLog;
import com.uniflow.entity.ThirdPartyIntegration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 数据同步执行器
 */
@Service
public class DataSyncExecutor {
    
    private static final Logger logger = LoggerFactory.getLogger(DataSyncExecutor.class);
    
    @Autowired
    private DataSyncService dataSyncService;
    
    @Autowired
    private DataSyncLogService dataSyncLogService;
    
    @Autowired
    private ThirdPartyIntegrationService thirdPartyIntegrationService;
    
    // 线程池用于异步执行同步任务
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);
    
    /**
     * 执行数据同步任务
     */
    @Transactional
    public boolean executeSync(String syncId, String triggeredBy, String triggeredByName, String triggerType) {
        try {
            // 获取同步任务
            DataSync dataSync = dataSyncService.getById(syncId, null);
            if (dataSync == null) {
                logger.error("数据同步任务不存在: {}", syncId);
                return false;
            }
            
            // 检查任务是否可执行
            if (!isExecutable(dataSync)) {
                logger.warn("数据同步任务不可执行: {}", syncId);
                return false;
            }
            
            // 创建执行日志
            DataSyncLog syncLog = createSyncLog(dataSync, triggeredBy, triggeredByName, triggerType);
            
            // 异步执行同步任务
            CompletableFuture.runAsync(() -> {
                executeAsyncSync(dataSync, syncLog);
            }, executorService);
            
            return true;
        } catch (Exception e) {
            logger.error("执行数据同步任务失败: {}", syncId, e);
            return false;
        }
    }
    
    /**
     * 批量执行数据同步任务
     */
    public boolean batchExecuteSync(List<String> syncIds, String triggeredBy, String triggeredByName, String triggerType) {
        try {
            for (String syncId : syncIds) {
                executeSync(syncId, triggeredBy, triggeredByName, triggerType);
            }
            return true;
        } catch (Exception e) {
            logger.error("批量执行数据同步任务失败", e);
            return false;
        }
    }
    
    /**
     * 停止数据同步任务
     */
    @Transactional
    public boolean stopSync(String syncId, String stoppedBy, String stoppedByName) {
        try {
            // 获取数据同步任务
            DataSync dataSync = dataSyncService.getById(syncId, null);
            if (dataSync == null) {
                return false;
            }
            
            // 更新任务状态为停止
            dataSyncService.updateExecutionStatus(syncId, "stopped", stoppedBy, stoppedByName);
            
            // 更新正在运行的日志状态
            List<DataSyncLog> runningLogs = dataSyncLogService.getRunningLogs(dataSync.getTenantId());
            for (DataSyncLog log : runningLogs) {
                if (syncId.equals(log.getSyncId())) {
                    dataSyncLogService.completeExecution(log.getId(), "stopped", "任务被手动停止", null);
                }
            }
            
            return true;
        } catch (Exception e) {
            logger.error("停止数据同步任务失败: {}", syncId, e);
            return false;
        }
    }
    
    /**
     * 重置数据同步任务
     */
    @Transactional
    public boolean resetSync(String syncId, String resetBy, String resetByName) {
        try {
            // 停止正在运行的任务
            stopSync(syncId, resetBy, resetByName);
            
            // 重置任务状态
            dataSyncService.updateExecutionStatus(syncId, "ready", resetBy, resetByName);
            
            // 清理执行统计
            Map<String, Object> executionStats = new HashMap<>();
            executionStats.put("totalExecutions", 0);
            executionStats.put("successfulExecutions", 0);
            executionStats.put("failedExecutions", 0);
            executionStats.put("lastExecutionTime", null);
            executionStats.put("lastSuccessTime", null);
            executionStats.put("lastFailureTime", null);
            executionStats.put("avgExecutionTime", 0);
            executionStats.put("successRate", 0.0);
            
            dataSyncService.updateExecutionStats(syncId, executionStats, "reset", null);
            
            return true;
        } catch (Exception e) {
            logger.error("重置数据同步任务失败: {}", syncId, e);
            return false;
        }
    }
    
    /**
     * 检查任务是否可执行
     */
    private boolean isExecutable(DataSync dataSync) {
        // 检查任务是否启用
        if (!dataSync.isEnabled()) {
            return false;
        }
        
        // 检查任务状态
        if ("running".equals(dataSync.getExecutionStatus()) || 
            "paused".equals(dataSync.getStatus()) ||
            "disabled".equals(dataSync.getStatus())) {
            return false;
        }
        
        // 检查依赖任务
        List<String> dependencies = dataSync.getDependencies();
        if (dependencies != null && !dependencies.isEmpty()) {
            for (String depId : dependencies) {
                if (depId != null && !depId.trim().isEmpty()) {
                    DataSync depTask = dataSyncService.getById(depId.trim(), dataSync.getTenantId());
                    if (depTask == null || !"completed".equals(depTask.getExecutionStatus())) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    /**
     * 创建同步日志
     */
    private DataSyncLog createSyncLog(DataSync dataSync, String triggeredBy, String triggeredByName, String triggerType) {
        DataSyncLog syncLog = new DataSyncLog();
        syncLog.setId(UUID.randomUUID().toString());
        syncLog.setSyncId(dataSync.getId());
        syncLog.setSyncName(dataSync.getName());
        syncLog.setBatchNo(generateBatchNo());
        syncLog.setStatus("running");
        syncLog.setTriggerType(triggerType);
        syncLog.setTriggeredBy(triggeredBy);
        syncLog.setTriggeredByName(triggeredByName);
        syncLog.setStartTime(LocalDateTime.now());
        syncLog.setProgress(0);
        syncLog.setTenantId(dataSync.getTenantId());
        // DataSyncLog实体可能没有这些字段，先注释掉
        // syncLog.setCreatedBy(triggeredBy);
        // syncLog.setCreatedByName(triggeredByName);
        syncLog.setCreatedTime(LocalDateTime.now());
        
        dataSyncLogService.createLog(syncLog);
        return syncLog;
    }
    
    /**
     * 异步执行同步任务
     */
    private void executeAsyncSync(DataSync dataSync, DataSyncLog syncLog) {
        LocalDateTime startTime = LocalDateTime.now();
        String status = "success";
        String errorMessage = null;
        int processedRecords = 0;
        int successRecords = 0;
        int failedRecords = 0;
        
        try {
            // 更新任务状态为运行中
            dataSyncService.updateExecutionStatus(dataSync.getId(), "running", 
                    syncLog.getTriggeredBy(), syncLog.getTriggeredByName());
            
            // 开始执行日志
            dataSyncLogService.startExecution(dataSync.getId(), dataSync.getName(), syncLog.getTriggerType(),
                    syncLog.getTriggeredBy(), syncLog.getTriggeredByName(), dataSync.getTenantId());
            
            // 执行具体的同步逻辑
            SyncResult result = performSync(dataSync, syncLog);
            
            processedRecords = result.getProcessedRecords();
            successRecords = result.getSuccessRecords();
            failedRecords = result.getFailedRecords();
            
            if (result.isSuccess()) {
                status = "success";
            } else {
                status = "failed";
                errorMessage = result.getErrorMessage();
            }
            
        } catch (Exception e) {
            logger.error("执行数据同步任务异常: {}", dataSync.getId(), e);
            status = "failed";
            errorMessage = e.getMessage();
        } finally {
            LocalDateTime endTime = LocalDateTime.now();
            long executionTime = java.time.Duration.between(startTime, endTime).toMillis();
            
            // 完成执行日志
            dataSyncLogService.completeExecution(syncLog.getId(), status, 
                    String.format("处理:%d, 成功:%d, 失败:%d", processedRecords, successRecords, failedRecords), 
                    errorMessage);
            
            // 更新任务执行状态
            String taskStatus = "success".equals(status) ? "completed" : "failed";
            dataSyncService.updateExecutionStatus(dataSync.getId(), taskStatus,
                    syncLog.getTriggeredBy(), syncLog.getTriggeredByName());
            
            // 更新任务执行统计
            updateExecutionStats(dataSync, status, executionTime);
        }
    }
    
    /**
     * 执行具体的同步逻辑
     */
    private SyncResult performSync(DataSync dataSync, DataSyncLog syncLog) {
        SyncResult result = new SyncResult();
        
        try {
            // 解析同步配置
            Map<String, Object> syncConfig = dataSync.getSyncConfigObject();
            String sourceType = dataSync.getSourceType();
            String targetType = dataSync.getTargetType();
            
            // 更新进度
            dataSyncLogService.updateProgress(syncLog.getId(), 10, "开始数据同步", 0);
            
            // 获取源数据
            List<Map<String, Object>> sourceData = getSourceData(dataSync, syncConfig);
            result.setProcessedRecords(sourceData.size());
            
            // 更新进度
            dataSyncLogService.updateProgress(syncLog.getId(), 30, "获取源数据完成", 100);
            
            // 数据转换
            List<Map<String, Object>> transformedData = transformData(dataSync, sourceData, syncConfig);
            
            // 更新进度
            dataSyncLogService.updateProgress(syncLog.getId(), 60, "数据转换完成", 100);
            
            // 写入目标数据
            SyncResult writeResult = writeTargetData(dataSync, transformedData, syncConfig);
            result.setSuccessRecords(writeResult.getSuccessRecords());
            result.setFailedRecords(writeResult.getFailedRecords());
            
            // 更新进度
            dataSyncLogService.updateProgress(syncLog.getId(), 90, "数据写入完成", 100);
            
            // 执行后处理
            postProcess(dataSync, syncConfig);
            
            // 更新进度
            dataSyncLogService.updateProgress(syncLog.getId(), 100, "同步完成", 100);
            
            result.setSuccess(true);
            
        } catch (Exception e) {
            logger.error("执行同步逻辑失败", e);
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取源数据
     */
    private List<Map<String, Object>> getSourceData(DataSync dataSync, Map<String, Object> syncConfig) {
        List<Map<String, Object>> data = new ArrayList<>();
        
        try {
            String sourceType = dataSync.getSourceType();
            Map<String, Object> sourceConfig = (Map<String, Object>) syncConfig.get("source");
            
            switch (sourceType.toLowerCase()) {
                case "database":
                    data = getDatabaseData(sourceConfig);
                    break;
                case "api":
                    data = getApiData(sourceConfig);
                    break;
                case "file":
                    data = getFileData(sourceConfig);
                    break;
                case "third_party":
                    data = getThirdPartyData(dataSync, sourceConfig);
                    break;
                default:
                    throw new RuntimeException("不支持的源数据类型: " + sourceType);
            }
        } catch (Exception e) {
            logger.error("获取源数据失败", e);
            throw e;
        }
        
        return data;
    }
    
    /**
     * 获取数据库数据
     */
    private List<Map<String, Object>> getDatabaseData(Map<String, Object> sourceConfig) {
        // 模拟数据库查询
        List<Map<String, Object>> data = new ArrayList<>();
        
        // 这里应该根据配置连接数据库并执行查询
        String sql = (String) sourceConfig.get("sql");
        String connectionString = (String) sourceConfig.get("connectionString");
        
        // 模拟返回数据
        for (int i = 1; i <= 100; i++) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", i);
            record.put("name", "Record " + i);
            record.put("value", Math.random() * 1000);
            record.put("created_time", LocalDateTime.now());
            data.add(record);
        }
        
        return data;
    }
    
    /**
     * 获取API数据
     */
    private List<Map<String, Object>> getApiData(Map<String, Object> sourceConfig) {
        // 模拟API调用
        List<Map<String, Object>> data = new ArrayList<>();
        
        String url = (String) sourceConfig.get("url");
        String method = (String) sourceConfig.get("method");
        Map<String, Object> headers = (Map<String, Object>) sourceConfig.get("headers");
        
        // 这里应该实际调用API
        // 模拟返回数据
        for (int i = 1; i <= 50; i++) {
            Map<String, Object> record = new HashMap<>();
            record.put("api_id", i);
            record.put("api_data", "API Data " + i);
            record.put("timestamp", System.currentTimeMillis());
            data.add(record);
        }
        
        return data;
    }
    
    /**
     * 获取文件数据
     */
    private List<Map<String, Object>> getFileData(Map<String, Object> sourceConfig) {
        // 模拟文件读取
        List<Map<String, Object>> data = new ArrayList<>();
        
        String filePath = (String) sourceConfig.get("filePath");
        String fileType = (String) sourceConfig.get("fileType");
        
        // 这里应该实际读取文件
        // 模拟返回数据
        for (int i = 1; i <= 200; i++) {
            Map<String, Object> record = new HashMap<>();
            record.put("file_id", i);
            record.put("file_content", "File Content " + i);
            record.put("line_number", i);
            data.add(record);
        }
        
        return data;
    }
    
    /**
     * 获取第三方系统数据
     */
    private List<Map<String, Object>> getThirdPartyData(DataSync dataSync, Map<String, Object> sourceConfig) {
        List<Map<String, Object>> data = new ArrayList<>();
        
        try {
            String integrationId = (String) sourceConfig.get("integrationId");
            ThirdPartyIntegration integration = thirdPartyIntegrationService.getById(integrationId, dataSync.getTenantId());
            
            if (integration == null) {
                throw new RuntimeException("第三方集成不存在: " + integrationId);
            }
            
            // 检查集成状态
            if (!integration.isConnected()) {
                throw new RuntimeException("第三方集成未连接: " + integration.getName());
            }
            
            // 根据集成类型获取数据
            String integrationType = integration.getIntegrationType();
            Map<String, Object> integrationConfig = integration.getIntegrationConfigObject();
            
            // 这里应该根据具体的第三方系统实现数据获取逻辑
            // 模拟返回数据
            for (int i = 1; i <= 150; i++) {
                Map<String, Object> record = new HashMap<>();
                record.put("third_party_id", i);
                record.put("third_party_data", "Third Party Data " + i);
                record.put("integration_type", integrationType);
                record.put("sync_time", LocalDateTime.now());
                data.add(record);
            }
            
        } catch (Exception e) {
            logger.error("获取第三方数据失败", e);
            throw e;
        }
        
        return data;
    }
    
    /**
     * 数据转换
     */
    private List<Map<String, Object>> transformData(DataSync dataSync, List<Map<String, Object>> sourceData, Map<String, Object> syncConfig) {
        List<Map<String, Object>> transformedData = new ArrayList<>();
        
        try {
            Map<String, Object> transformConfig = (Map<String, Object>) syncConfig.get("transform");
            if (transformConfig == null) {
                return sourceData; // 无转换配置，直接返回原数据
            }
            
            Map<String, Object> fieldMapping = (Map<String, Object>) transformConfig.get("fieldMapping");
            Map<String, Object> dataValidation = (Map<String, Object>) transformConfig.get("dataValidation");
            
            for (Map<String, Object> sourceRecord : sourceData) {
                Map<String, Object> transformedRecord = new HashMap<>();
                
                // 字段映射
                if (fieldMapping != null) {
                    for (String sourceField : fieldMapping.keySet()) {
                        String targetField = (String) fieldMapping.get(sourceField);
                        if (sourceRecord.containsKey(sourceField)) {
                            transformedRecord.put(targetField, sourceRecord.get(sourceField));
                        }
                    }
                } else {
                    transformedRecord.putAll(sourceRecord);
                }
                
                // 数据验证
                if (dataValidation != null && validateRecord(transformedRecord, dataValidation)) {
                    transformedData.add(transformedRecord);
                } else if (dataValidation == null) {
                    transformedData.add(transformedRecord);
                }
            }
            
        } catch (Exception e) {
            logger.error("数据转换失败", e);
            throw e;
        }
        
        return transformedData;
    }
    
    /**
     * 验证记录
     */
    private boolean validateRecord(Map<String, Object> record, Map<String, Object> validationConfig) {
        // 实现数据验证逻辑
        // 这里简化处理，实际应该根据验证规则进行验证
        return true;
    }
    
    /**
     * 写入目标数据
     */
    private SyncResult writeTargetData(DataSync dataSync, List<Map<String, Object>> transformedData, Map<String, Object> syncConfig) {
        SyncResult result = new SyncResult();
        int successCount = 0;
        int failedCount = 0;
        
        try {
            String targetType = dataSync.getTargetType();
            Map<String, Object> targetConfig = (Map<String, Object>) syncConfig.get("target");
            
            switch (targetType.toLowerCase()) {
                case "database":
                    SyncResult dbResult = writeDatabaseData(transformedData, targetConfig);
                    successCount = dbResult.getSuccessRecords();
                    failedCount = dbResult.getFailedRecords();
                    break;
                case "api":
                    SyncResult apiResult = writeApiData(transformedData, targetConfig);
                    successCount = apiResult.getSuccessRecords();
                    failedCount = apiResult.getFailedRecords();
                    break;
                case "file":
                    SyncResult fileResult = writeFileData(transformedData, targetConfig);
                    successCount = fileResult.getSuccessRecords();
                    failedCount = fileResult.getFailedRecords();
                    break;
                case "third_party":
                    SyncResult tpResult = writeThirdPartyData(dataSync, transformedData, targetConfig);
                    successCount = tpResult.getSuccessRecords();
                    failedCount = tpResult.getFailedRecords();
                    break;
                default:
                    throw new RuntimeException("不支持的目标数据类型: " + targetType);
            }
            
            result.setSuccessRecords(successCount);
            result.setFailedRecords(failedCount);
            result.setSuccess(failedCount == 0);
            
        } catch (Exception e) {
            logger.error("写入目标数据失败", e);
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 写入数据库数据
     */
    private SyncResult writeDatabaseData(List<Map<String, Object>> data, Map<String, Object> targetConfig) {
        SyncResult result = new SyncResult();
        
        // 模拟数据库写入
        int successCount = 0;
        int failedCount = 0;
        
        for (Map<String, Object> record : data) {
            try {
                // 这里应该实际执行数据库插入/更新操作
                // 模拟成功
                successCount++;
            } catch (Exception e) {
                failedCount++;
                logger.error("写入数据库记录失败", e);
            }
        }
        
        result.setSuccessRecords(successCount);
        result.setFailedRecords(failedCount);
        return result;
    }
    
    /**
     * 写入API数据
     */
    private SyncResult writeApiData(List<Map<String, Object>> data, Map<String, Object> targetConfig) {
        SyncResult result = new SyncResult();
        
        // 模拟API写入
        int successCount = 0;
        int failedCount = 0;
        
        for (Map<String, Object> record : data) {
            try {
                // 这里应该实际调用API
                // 模拟成功
                successCount++;
            } catch (Exception e) {
                failedCount++;
                logger.error("写入API记录失败", e);
            }
        }
        
        result.setSuccessRecords(successCount);
        result.setFailedRecords(failedCount);
        return result;
    }
    
    /**
     * 写入文件数据
     */
    private SyncResult writeFileData(List<Map<String, Object>> data, Map<String, Object> targetConfig) {
        SyncResult result = new SyncResult();
        
        // 模拟文件写入
        int successCount = data.size();
        int failedCount = 0;
        
        try {
            // 这里应该实际写入文件
            // 模拟成功
        } catch (Exception e) {
            successCount = 0;
            failedCount = data.size();
            logger.error("写入文件失败", e);
        }
        
        result.setSuccessRecords(successCount);
        result.setFailedRecords(failedCount);
        return result;
    }
    
    /**
     * 写入第三方系统数据
     */
    private SyncResult writeThirdPartyData(DataSync dataSync, List<Map<String, Object>> data, Map<String, Object> targetConfig) {
        SyncResult result = new SyncResult();
        
        try {
            String integrationId = (String) targetConfig.get("integrationId");
            ThirdPartyIntegration integration = thirdPartyIntegrationService.getById(integrationId, dataSync.getTenantId());
            
            if (integration == null) {
                throw new RuntimeException("第三方集成不存在: " + integrationId);
            }
            
            // 检查集成状态
            if (!integration.isConnected()) {
                throw new RuntimeException("第三方集成未连接: " + integration.getName());
            }
            
            // 模拟第三方系统写入
            int successCount = 0;
            int failedCount = 0;
            
            for (Map<String, Object> record : data) {
                try {
                    // 这里应该根据具体的第三方系统实现数据写入逻辑
                    // 模拟成功
                    successCount++;
                } catch (Exception e) {
                    failedCount++;
                    logger.error("写入第三方系统记录失败", e);
                }
            }
            
            result.setSuccessRecords(successCount);
            result.setFailedRecords(failedCount);
            
        } catch (Exception e) {
            logger.error("写入第三方数据失败", e);
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 后处理
     */
    private void postProcess(DataSync dataSync, Map<String, Object> syncConfig) {
        try {
            Map<String, Object> postProcessConfig = (Map<String, Object>) syncConfig.get("postProcess");
            if (postProcessConfig == null) {
                return;
            }
            
            // 执行后处理逻辑
            // 例如：发送通知、清理临时数据、更新状态等
            
        } catch (Exception e) {
            logger.error("后处理失败", e);
            // 后处理失败不影响主流程
        }
    }
    
    /**
     * 更新执行统计
     */
    private void updateExecutionStats(DataSync dataSync, String status, long executionTime) {
        try {
            Map<String, Object> currentStats = dataSync.getExecutionStatsObject();
            if (currentStats == null) {
                currentStats = new HashMap<>();
            }
            
            // 更新统计信息
            int totalExecutions = (Integer) currentStats.getOrDefault("totalExecutions", 0) + 1;
            int successfulExecutions = (Integer) currentStats.getOrDefault("successfulExecutions", 0);
            int failedExecutions = (Integer) currentStats.getOrDefault("failedExecutions", 0);
            
            if ("success".equals(status)) {
                successfulExecutions++;
                currentStats.put("lastSuccessTime", LocalDateTime.now());
            } else {
                failedExecutions++;
                currentStats.put("lastFailureTime", LocalDateTime.now());
            }
            
            currentStats.put("totalExecutions", totalExecutions);
            currentStats.put("successfulExecutions", successfulExecutions);
            currentStats.put("failedExecutions", failedExecutions);
            currentStats.put("lastExecutionTime", LocalDateTime.now());
            
            // 计算平均执行时间
            long avgExecutionTime = (Long) currentStats.getOrDefault("avgExecutionTime", 0L);
            avgExecutionTime = (avgExecutionTime * (totalExecutions - 1) + executionTime) / totalExecutions;
            currentStats.put("avgExecutionTime", avgExecutionTime);
            
            // 计算成功率
            double successRate = totalExecutions > 0 ? (double) successfulExecutions / totalExecutions * 100 : 0;
            currentStats.put("successRate", successRate);
            
            // 更新到数据库
            dataSyncService.updateExecutionStats(dataSync.getId(), currentStats, status, null);
            
        } catch (Exception e) {
            logger.error("更新执行统计失败", e);
        }
    }
    
    /**
     * 生成批次号
     */
    private String generateBatchNo() {
        return "BATCH_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }
    
    /**
     * 关闭执行器
     */
    public void shutdown() {
        try {
            executorService.shutdown();
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 同步结果类
     */
    public static class SyncResult {
        private boolean success;
        private String errorMessage;
        private int processedRecords;
        private int successRecords;
        private int failedRecords;
        
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        
        public int getProcessedRecords() { return processedRecords; }
        public void setProcessedRecords(int processedRecords) { this.processedRecords = processedRecords; }
        
        public int getSuccessRecords() { return successRecords; }
        public void setSuccessRecords(int successRecords) { this.successRecords = successRecords; }
        
        public int getFailedRecords() { return failedRecords; }
        public void setFailedRecords(int failedRecords) { this.failedRecords = failedRecords; }
    }
}